package com.lxl.servlet;

import com.lxl.config.SystemConfig;
import com.lxl.core.TaskExecutor;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public abstract class BaseShortServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final AsyncContext ctx;
        configServletSupportedAsync(request);
        ctx = getContextWithTimeoutConfig(request);
        getTask(ctx).start();
        response.getWriter().flush();
    }

    private void configServletSupportedAsync(HttpServletRequest request){
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
    }

    private AsyncContext getContextWithTimeoutConfig(HttpServletRequest request){
        AsyncContext ctx = request.startAsync();
        ctx.setTimeout(SystemConfig.SERVLET_ASYNC_TIMEOUT);
        return ctx;
    }

    abstract protected TaskExecutor getTask(AsyncContext context);
}
